package com.newway.wechat.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.newway.common.Result;
import com.newway.wechat.entity.chat.ChatHistory;
import com.newway.wechat.entity.chat.ChatMessage;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

import static com.newway.config.RedisChatMemory.DEFAULT_KEY_PREFIX;

@RequestMapping("/wechat/ai")
@RestController
public class ChatController {


    @Autowired
    StringRedisTemplate stringRedisTemplate;
    /**
     * 对话历史记录
     */
    private Map<String, ChatHistory> historyMap = new LinkedHashMap<>();


    @Autowired
    private ChatClient chatClient;

    @GetMapping("/chat")
    public Result<String> chat(@RequestParam(value = "input") String input) {
        String content = this.chatClient.prompt()
                .user(input)
                .call()
                .content();
        return Result.success(content);
    }

    /**
     * 流式输出样例
     * @param input
     * @return
     */
    @GetMapping(value="/flux")
    public Flux<String> chatRes(@RequestParam(value = "input") String input, HttpServletRequest request){
        //添加记录
        historyMap.putIfAbsent(request.getSession().getId(),new ChatHistory(request.getSession().getId(),input,new Date().toLocaleString(),new ArrayList<>()));

        Flux<String> output = chatClient.prompt()
                .advisors(a->a.param(MessageChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY,request.getSession().getId()))
                .user(input)
                .stream()
                .content();
        return output;
    }


    /**
     * 获取历史记录
     * @return
     */
    @GetMapping("/history")
    public Result getChatHistory(){
        Collection<ChatHistory> values = historyMap.values();
        List<ChatHistory> list = new ArrayList<>(values);
        // 对 List 进行倒序排序
        List<ChatHistory> result = new ArrayList<>();
        for(int i=list.size()-1;i>=0;i--){
            result.add(list.get(i));
        }
        return Result.success(result);
    }

    /**
     * 获取记录详情
     * @param id
     * @return
     */
    @GetMapping("/historyDetails/{id}")
    public Result getChatHistory(@PathVariable("id")String id){
        List<String> messageStrings = stringRedisTemplate.opsForList().range(DEFAULT_KEY_PREFIX.concat(id), 0, -1);
        List<ChatMessage> result = new ArrayList<>();
        for(String str: messageStrings){
            JSONArray objects = JSON.parseArray(str);
            JSONObject temp = (JSONObject)objects.get(0);
            String messageType = temp.getString("messageType");
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setRole(temp.getString("messageType"));
            if(messageType.equals("USER")){
                chatMessage.setContent(temp.getString("content"));
            }else {
                chatMessage.setAnswer(temp.getString("content"));
            }
            chatMessage.setThink("");
            chatMessage.setShowThink(false);
            result.add(chatMessage);
        }
        return Result.success(result);
    }

    @RequestMapping({"/sendMsg"})
    public String sendMsg(String phoneNo) throws Exception {
        int randomSixDigits = ThreadLocalRandom.current().nextInt(100000, 1000000);
        String content = "您的验证码是{" + randomSixDigits + "}。如非本人操作，请忽略本短信";
        String url = String.format("%s?u=%s&p=%s&m=%s&c=%s",
                "http://api.smsbao.com/sms",
                URLEncoder.encode("qqq154060", "UTF-8"),
                URLEncoder.encode(md5("sanren123"), "UTF-8"),
                URLEncoder.encode("15038710807", "UTF-8"),
                URLEncoder.encode(null + "海南时光密码", "UTF-8"));

        // 发送HTTP GET请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);

        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            EntityUtils.consume(entity);

            // 解析返回结果
            return parseResult(result);
        }
    }

    public static String md5(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(str.getBytes());
            StringBuilder sb = new StringBuilder();
            byte[] var4 = array;
            int var5 = array.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                byte b = var4[var6];
                sb.append(String.format("%02x", b));
            }

            return sb.toString();
        } catch (NoSuchAlgorithmException var8) {
            var8.printStackTrace();
            return null;
        }
    }

    private String parseResult(String result) {
        switch (result) {
            case "0":
                return "短信发送成功";
            case "30":
                return "密码错误";
            case "40":
                return "账号不存在";
            case "41":
                return "余额不足";
            case "43":
                return "IP地址限制";
            case "50":
                return "内容含有敏感词";
            case "51":
                return "手机号码不正确";
            default:
                return "未知错误";
        }
    }
}
